<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>报警设置 - 智能水产养殖系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-4">
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="text-danger">
                <i class="bi bi-exclamation-triangle"></i> 报警阈值设置
            </h2>
            <p class="text-muted">设置水质参数的异常阈值，系统将自动监控并发出报警</p>
        </div>
    </div>

    <!-- 实时监控状态 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card shadow">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-speedometer2"></i> 实时监控状态
                        <span id="status-badge" class="badge bg-success float-end">正常</span>
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row" id="realtime-data">
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 id="current-temp">--</h4>
                                <small class="text-muted">当前水温 (℃)</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 id="current-ph">--</h4>
                                <small class="text-muted">当前pH值</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 id="current-do">--</h4>
                                <small class="text-muted">当前溶解氧 (mg/L)</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 id="alarm-count">0</h4>
                                <small class="text-muted">当前报警数</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 阈值设置表单 -->
    <div class="row">
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="bi bi-gear"></i> 报警阈值设置</h5>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="text-primary">水温设置 (℃)</h6>
                                <div class="mb-3">
                                    <label class="form-label">最低水温阈值</label>
                                    <input type="number" step="0.1" name="min_temp" class="form-control" 
                                           value="{{ thresholds.temperature.min }}" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">最高水温阈值</label>
                                    <input type="number" step="0.1" name="max_temp" class="form-control" 
                                           value="{{ thresholds.temperature.max }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="text-success">pH值设置</h6>
                                <div class="mb-3">
                                    <label class="form-label">最低pH阈值</label>
                                    <input type="number" step="0.1" name="min_ph" class="form-control" 
                                           value="{{ thresholds.ph.min }}" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">最高pH阈值</label>
                                    <input type="number" step="0.1" name="max_ph" class="form-control" 
                                           value="{{ thresholds.ph.max }}" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="text-info">溶解氧设置 (mg/L)</h6>
                                <div class="mb-3">
                                    <label class="form-label">最低溶解氧阈值</label>
                                    <input type="number" step="0.1" name="min_do" class="form-control" 
                                           value="{{ thresholds.dissolved_oxygen.min }}" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">最高溶解氧阈值</label>
                                    <input type="number" step="0.1" name="max_do" class="form-control" 
                                           value="{{ thresholds.dissolved_oxygen.max }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="text-warning">浊度设置 (NTU)</h6>
                                <div class="mb-3">
                                    <label class="form-label">最低浊度阈值</label>
                                    <input type="number" step="0.1" name="min_turbidity" class="form-control" 
                                           value="{{ thresholds.turbidity.min }}" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">最高浊度阈值</label>
                                    <input type="number" step="0.1" name="max_turbidity" class="form-control" 
                                           value="{{ thresholds.turbidity.max }}" required>
                                </div>
                            </div>
                        </div>
                        <div class="text-center">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> 保存设置
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header bg-warning text-dark">
                    <h5 class="mb-0"><i class="bi bi-bell"></i> 报警说明</h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <h6>水温报警</h6>
                        <p class="mb-2">水温过高或过低会影响鱼类生长，建议保持在15-25℃范围内。</p>
                    </div>
                    <div class="alert alert-success">
                        <h6>pH值报警</h6>
                        <p class="mb-2">pH值异常会影响鱼类健康，正常范围应在6.5-8.5之间。</p>
                    </div>
                    <div class="alert alert-primary">
                        <h6>溶解氧报警</h6>
                        <p class="mb-2">溶解氧不足会导致鱼类缺氧，建议保持在6-12mg/L范围内。</p>
                    </div>
                    <div class="alert alert-warning">
                        <h6>浊度报警</h6>
                        <p class="mb-2">浊度过高会影响水质透明度，建议控制在0-50NTU范围内。</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-4">
        <div class="col-12 text-center">
            <a href="{{ url_for('alarm_records') }}" class="btn btn-outline-danger">
                <i class="bi bi-list-ul"></i> 查看报警记录
            </a>
            <a href="{{ url_for('user_home') }}" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> 返回主页
            </a>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// 实时数据更新
function updateRealtimeData() {
    console.log('开始获取实时数据...');
    
    // 先测试简单API连接
    fetch('/api/test')
    .then(response => {
        console.log('测试API响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`测试API失败: HTTP ${response.status}`);
        }
        return response.json();
    })
    .then(testData => {
        console.log('测试API成功:', testData);
        
        // 测试成功后，获取报警数据
        return fetch('/api/check_alarms', {
            method: 'GET',
            credentials: 'same-origin'
        });
    })
    .then(response => {
        console.log('报警API响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`报警API失败: HTTP ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('获取到的报警数据:', data);
        
        if (data.current_data) {
            document.getElementById('current-temp').textContent = data.current_data.temperature + '℃';
            document.getElementById('current-ph').textContent = data.current_data.ph;
            document.getElementById('current-do').textContent = data.current_data.dissolved_oxygen + 'mg/L';
        }
        
        document.getElementById('alarm-count').textContent = data.alarm_count || 0;
        
        const statusBadge = document.getElementById('status-badge');
        if (data.alarm_count > 0) {
            statusBadge.textContent = '异常';
            statusBadge.className = 'badge bg-danger float-end';
        } else {
            statusBadge.textContent = '正常';
            statusBadge.className = 'badge bg-success float-end';
        }
    })
    .catch(error => {
        console.error('获取实时数据失败:', error);
        document.getElementById('current-temp').textContent = '--';
        document.getElementById('current-ph').textContent = '--';
        document.getElementById('current-do').textContent = '--';
        document.getElementById('alarm-count').textContent = '--';
        
        const statusBadge = document.getElementById('status-badge');
        statusBadge.textContent = '连接失败';
        statusBadge.className = 'badge bg-warning float-end';
    });
}

// 显示报警详情
function showAlarmDetails(alarms) {
    // 移除旧的报警详情
    const existingDetails = document.getElementById('alarm-details');
    if (existingDetails) {
        existingDetails.remove();
    }
    
    // 创建报警详情区域
    const detailsDiv = document.createElement('div');
    detailsDiv.id = 'alarm-details';
    detailsDiv.className = 'row mt-3';
    
    alarms.forEach(alarm => {
        const alarmCard = document.createElement('div');
        alarmCard.className = 'col-md-6 mb-2';
        alarmCard.innerHTML = `
            <div class="alert alert-${alarm.severity === 'high' ? 'danger' : 'warning'} alert-dismissible fade show">
                <strong>${alarm.type === 'temperature' ? '🌡️ 水温' : 
                         alarm.type === 'ph' ? '🧪 pH值' : 
                         alarm.type === 'dissolved_oxygen' ? '💧 溶解氧' : '🌊 浊度'} 异常</strong><br>
                <small>${alarm.message}</small>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        detailsDiv.appendChild(alarmCard);
    });
    
    // 插入到实时监控状态卡片中
    const realtimeCard = document.querySelector('.card-body');
    if (realtimeCard) {
        realtimeCard.appendChild(detailsDiv);
    }
}

// 显示错误信息
function showErrorMessage(message) {
    // 移除旧的错误信息
    const existingError = document.getElementById('error-message');
    if (existingError) {
        existingError.remove();
    }
    
    // 创建错误信息区域
    const errorDiv = document.createElement('div');
    errorDiv.id = 'error-message';
    errorDiv.className = 'row mt-3';
    errorDiv.innerHTML = `
        <div class="col-12">
            <div class="alert alert-warning alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle"></i> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
    `;
    
    // 插入到实时监控状态卡片中
    const realtimeCard = document.querySelector('.card-body');
    if (realtimeCard) {
        realtimeCard.appendChild(errorDiv);
    }
}

// 添加闪烁动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes blink {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }
`;
document.head.appendChild(style);

// 页面加载完成后开始实时更新
document.addEventListener('DOMContentLoaded', function() {
    console.log('报警设置页面加载完成，开始实时监控...');
    
    // 立即执行一次
    updateRealtimeData();
    
    // 每5秒更新一次数据
    setInterval(updateRealtimeData, 5000);
    
    // 添加手动刷新按钮
    const refreshButton = document.createElement('button');
    refreshButton.className = 'btn btn-outline-info btn-sm position-fixed';
    refreshButton.style.cssText = 'top: 20px; right: 20px; z-index: 1000;';
    refreshButton.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 刷新监控';
    refreshButton.onclick = function() {
        console.log('手动刷新数据...');
        updateRealtimeData();
    };
    document.body.appendChild(refreshButton);
});
</script>

</body>
</html> 